/*
 * Scenario window
 */


MyDesktop.ScenariosModule = Ext.extend(Ext.app.Module, {
    id:'scenario-win',
    init : function() {
        this.launcher = {
            text: 'Scenario',
            iconCls:'icon-grid',
            handler : this.createWindow,
            scope: this
        }
    },

    createWindow : function(src) {
        var winId = 'scenario-win-' + src.windowId;
        var statusBarId = 'statusBar-' + src.windowId;
        var desktop = this.app.getDesktop();
        var app = this.app;
        var win = desktop.getWindow(winId);
        var scenarioGridId = "scenario-grid-" + src.scenario;

        function updateStatusBar(busy) {
            var sb = Ext.getCmp(statusBarId);
            if (busy) {
                sb.showBusy();
            } else {
                sb.clearStatus({useDefaults:true});
            }
        }

        if (!win) {

            var cookiesForPageStore = new Ext.data.ArrayStore({
                autoDestroy: true,
                fields: ['index', 'pageId'],
                data : []
            });
            var cookiesForPageCombo = new Ext.form.ComboBox({
                store: cookiesForPageStore,
                valueField:'index',
                displayField:'pageId',
                typeAhead: true,
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                emptyText:'No cookie selected',
                selectOnFocus:true
            });

            var propsGrid = new Ext.chloroform.ScenarioPropertyGrid({
                cookiesForPageStore: cookiesForPageStore,
                cookiesForPageCombo: cookiesForPageCombo
            });

            cookiesForPageCombo.on("select", function(combo, record, index) {
                propsGrid.selectCookie(index);
            });

            var propsPanel = new Ext.Panel({
                title: 'Navigation',
                region:'east',
                floatable: false,
                margins: '5 0 0 0',
                cmargins: '5 5 0 0',
                padding: '0 0 0 0',
                width: 200,
                minSize: 100,
                maxSize: 250,
//
                layout: {
                    type:'vbox',
                    padding:'2',
                    align:'stretch'
                },
//                autoHeight: true,

                items: [cookiesForPageCombo, propsGrid]
            });

            var paracol = src.paracol;

            propsGrid.on('afteredit', function (e) {
                // update the cookie model
                var pageCookies = this.cookiesModel.entries[this.pageName].cookies;
                var cookieIndex = propsGrid.getCookieIndex();
                var pageCookie = pageCookies[cookieIndex];
                pageCookie.fieldsObject[e.record.id].value = e.value;

                // send the change to the server
                //paracol.updatePreConfigCookieProperty(this.pageName, cookieIndex, e.record.id, e.value, null);
                paracol.updatePreConfigCookieProperty(this.pageName, cookieIndex, e.record.id, pageCookie.fieldsObject[e.record.id], null, {
                    target: "propertySheet"
                });

            }, propsGrid);

            var saveProjectHandler = function() {
                paracol.saveProject({
                    onProjectSaved : function() {
                        alert("Project saved!");
                    }
                })
            };

            var refresh = function(scenarioGridId, pageNameToSelect, afterRefresh) {

                //app.showWaitBox("Loading scenario");
                updateStatusBar(true);

                // get the fresh pre-config cookies model from the server
                paracol.getAllPreConfigCookies(src.scenario, {
                    onEditAllPreConfigCookies: function(message, data) {
                        // the fresh pre-config cookies have arrived
                        propsGrid.onEditAllPreConfigCookies(message, data);

                        // reload the scenario grid store and select the new node
                        var scGrid = Ext.getCmp(scenarioGridId);
                        var store = scGrid.getStore();

                        if (!pageNameToSelect) {
                            var selected = scGrid.getSelectionModel().getSelected();
                            if (selected && selected.data.id) {
                                pageNameToSelect = selected.data.id;
                            }
                        }

                        store.addListener("load", function() {
                            if (pageNameToSelect) {
                                var newPageIndex = store.find("id", pageNameToSelect);
                                scGrid.getSelectionModel().selectRow(newPageIndex);
                            } else {
                                scGrid.getSelectionModel().selectFirstRow();
                            }

                            if (afterRefresh) afterRefresh();

                            //app.hideWaitBox();
                            updateStatusBar(false);


                        }, this, {
                            single: true // remove the listener after the event is processed
                        });
                        store.reload();

                    }
                }, {
                    target: "propertySheet"
                });
            };

            var openNewProjectEntryWindow = function(scenarioGridId, contextEntryId) {
                var newEntryWindowFact = new Ext.app.NewProjectEntryWindow({
                    contextEntryId: contextEntryId,
                    app: app,
                    listeners: {
                        entryAdded: function(ev) {
                            refresh(scenarioGridId, ev.pageName, function() {
                                if (ev.preconfigurePage) {
                                    startConfig(scenarioGridId, ev.fullPageName, {
                                        // Cookie wizard configuration
                                        finishButtonDisabled: true, // no Final button

                                        extButtons: [
                                            { // extending button for sending the save memento message
                                                id: 'save-memento-button',
                                                text: 'Save',
                                                handler: function(btn, btnEvent, cookieWindow) {
                                                    // the third argument is artificially added by CookieWindow which wraps
                                                    // this handler

                                                    // sending the SaveMemento hint message
                                                    paracol.postCustomJsonMessage("POST", paracol.dispatcherUrl, {
                                                        onResponse: function(msg, ctx) {
                                                            cookieWindow.close();
                                                        }
                                                    }, {
                                                        msgType: "OpenHint",
                                                        id: "SaveMementoMenu",
                                                        type: "",
                                                        cookies: [
                                                            {
                                                                name: ev.pageName
                                                            }
                                                        ]
                                                    });
                                                }
                                            }
                                        ]});
                                }
                            });
                        }
                    }
                });
                newEntryWindowFact.createWindow(src.scenario, null /*metaPage filter*/, paracol);
            };


            var removeSelectedEntry = function(scenarioGridId) {
                //var scGrid = Ext.getCmp(scenarioGridId);
                var scGrid = Ext.getCmp(scenarioGridId);

                var selected = scGrid.getSelectionModel().getSelected();
                if (!selected) {
                    alert("No node selected");
                    return;
                }

                paracol.removeEntry(selected.data.id, {
                    onProjectEntryRemoved: function() {
                        var store = scGrid.getStore();
                        store.addListener("load", function() {
                            scGrid.getSelectionModel().selectFirstRow();
                        }, this, {
                            single: true // remove the listener after the event is processed
                        });
                        store.reload();
                    }
                })
            };

            var moveSelectedExtension = function(scenarioGridId, delta) {
                var scGrid = Ext.getCmp(scenarioGridId);

                var selected = scGrid.getSelectionModel().getSelected();
                var selectedId = selected.data.id;
                if (!selected) {
                    alert("No node selected");
                    return;
                }

                paracol.moveSelectedExtension(selectedId, delta, {
                    onExtensionMoved: function() {
                        var store = scGrid.getStore();
                        store.addListener("load", function() {
                            var selRec = store.getById(selectedId);
                            scGrid.getSelectionModel().selectRecords([selRec]);
                        }, this, {
                            single: true // remove the listener after the event is processed
                        });
                        store.reload();
                    }
                })
            };

            var projectModelUrl = src.projectModelUrl;

            var expander = new Ext.chloroform.ScenariosRowExpander({
                projectModelUrl: projectModelUrl + 'ext?extPath=',
                pageSelectionListener: propsGrid,
                openNewExtensionWindow: openNewProjectEntryWindow,
                removeSelectedExtension: removeSelectedEntry,
                extensionMover: moveSelectedExtension
            });
            var scenarioGrid = new Ext.chloroform.ScenariosGrid({
                id: scenarioGridId,
                projectModelUrl: projectModelUrl + '?scenario=' + src.scenario,
                expander: expander,
                pageSelectionListener: propsGrid,

                tbar : [
                    {
                        text:'Save Project',
                        tooltip:'Save the project',
                        iconCls:'add',
                        handler: function() {
                            saveProjectHandler();
                        }
                    },
                    '-',
                    {
                        text:'Add Node',
                        tooltip:'Add a new node',
                        iconCls:'add',
                        handler: function() {
                            openNewProjectEntryWindow(scenarioGridId);
                        }
                    },
                    '-',
                    {
                        text:'Remove Node',
                        tooltip:'Remove the selected node',
                        iconCls:'remove',
                        handler: function() {
                            removeSelectedEntry(scenarioGridId);
                        }
                    },
                    '-',
                    {
                        text:'Refresh',
                        tooltip:'Refresh',
                        iconCls:'option',
                        handler: function() {
                            refresh(scenarioGrid);
                        }
                    },
                    '-',
                    {
                        text:'Options',
                        tooltip:'Blah blah blah blaht',
                        iconCls:'option'
                    }
                ]

            });

            var selModel = scenarioGrid.getSelectionModel();

            scenarioGrid.getStore().on("load", function() {
                selModel.selectFirstRow();
            });

            scenarioGrid.on("viewready", function() {
                selModel.selectFirstRow();
            });

            var app = this.app;

            function startConfig(scenarioGridId, pageName, cookieWizardConfig) {
                if (!pageName) {
                    pageName = selModel.getSelected().data.id;
                }

                var cookieWinFact = new Ext.app.CookieWindow({
                    app: app
                });
                var cookieWindow = cookieWinFact.createWindow(pageName, cookieWizardConfig, paracol);
                cookieWindow.on("close", function() {
                    refresh(scenarioGridId, pageName);
                })

            }

            scenarioGrid.on("keydown", function(ev) {
                if (ev.getKey() == 13) {
                    startConfig(scenarioGridId);
                }
            });

            scenarioGrid.on("dblclick", function(ev) {
                startConfig(scenarioGridId);
            });

            var border = {
                //id:'border-panel',
                //title: 'Border Layout',
                layout: 'border',
                bodyBorder: false,
                defaults: {
                    collapsible: true,
                    split: true,
                    animFloat: false,
                    autoHide: false,
                    useSplitTips: true,
                    bodyStyle: 'padding:15px'
                },
                items: [
                    {
                        title: 'Footer',
                        region: 'south',
                        height: 150,
                        minSize: 75,
                        maxSize: 250,
                        cmargins: '5 0 0 0',
                        html: '<p>Footer content</p>'
                    },
                    propsPanel,
                    scenarioGrid
                ]
            };

            var sbar = new Ext.ux.StatusBar({
                //renderTo: 'basic',
                id: statusBarId,
                //width: 550,
                // defaults to use when the status is cleared:
                defaultText: 'Ready',
                //defaultIconCls: 'default-icon',

                // values to set initially:
                text: 'Ready',
                iconCls: 'x-status-valid',

                items: []
            });

            win = desktop.createWindow({
                id: winId,
                title: src.text + ' Scenario',
                width:800,
                height:600,
                iconCls: 'icon-grid',
                shim:false,
                animCollapse:false,
                constrainHeader:true,

                bbar: sbar,

                layout: 'fit',
                items: border
            });

            win.show();
            win.on("show", function() {
                refresh(scenarioGridId);
            });


        } else {
            win.show();
        }


    }
});
